package com.share.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.share.constants.CacheConstants;
import com.share.mapper.DriverSettingMapper;
import com.share.pojo.bo.DriverGeoBo;
import com.share.pojo.domain.DriverSetting;
import com.share.pojo.domain.RedisDriverSetting;
import com.share.result.JSONResult;
import com.share.service.IDriverWorkService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DriverWorkServiceImpl implements IDriverWorkService {
    @Autowired
    private DriverSettingMapper driverSettingMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void onLine() {
        long id = StpUtil.getLoginIdAsLong();//司机id
        DriverSetting driverSetting = driverSettingMapper.selectById(id);//查询司机的配置
        RedisDriverSetting redisDriverSetting = new RedisDriverSetting();
        BeanUtils.copyProperties(driverSetting,redisDriverSetting);
        String key = String.format(CacheConstants.KEY_DRIVER_ONLINE, id);
        //为什么设置5分钟过期
        redisTemplate.opsForValue().set(key,redisDriverSetting,5, TimeUnit.HOURS);
    }

    @Override
    public void offLine(Long id) {
        redisTemplate.delete(String.format(CacheConstants.KEY_DRIVER_ONLINE, id));
        redisTemplate.opsForGeo().remove(CacheConstants.GEO , StpUtil.getLoginIdAsLong());
    }

    @Override
    public void geo(DriverGeoBo driverGeoBo) {
        Point point = new Point(driverGeoBo.getLongitude(), driverGeoBo.getLatitude());
        Long add = redisTemplate.opsForGeo().add(CacheConstants.GEO, point, StpUtil.getLoginIdAsLong());
        if(add == 1){
            //重置过期时间
            String key = String.format(CacheConstants.KEY_DRIVER_ONLINE, StpUtil.getLoginIdAsLong());
            redisTemplate.expire(key,5,TimeUnit.HOURS);
        }
        //远程调用 大数据 库进行存储每一次坐标
    }

    @Override
    public JSONResult getGeo(Long driverId) {
        List<Point> position = redisTemplate.opsForGeo().position(CacheConstants.GEO, driverId);
        if(position.size() != 0){
            return JSONResult.success(position.get(0));
        }
        return JSONResult.error();
    }
}
